package com.chaoyer.cynet.access;

import com.chaoyer.cynet.access.handler.http.HttpServerHandler;
import com.chaoyer.cynet.access.handler.websocket.WebSocketHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.HttpServerExpectContinueHandler;
import io.netty.handler.codec.http.cors.CorsConfig;
import io.netty.handler.codec.http.cors.CorsConfigBuilder;
import io.netty.handler.codec.http.cors.CorsHandler;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class AcessServerChannelInitalizer extends ChannelInitializer<SocketChannel> {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    private final String[] CORS_ALLOW_HEADERS = {                // 可允许的请求头
            "accept",
            "accept-encoding",
            "authorization",
            "content-type",
            "origin",
            "user-agent",
            "x-csrftoken",
            "x-requested-with",
    };


    @Override
    protected void initChannel(SocketChannel ch) throws Exception {

        // cors跨域设置
        CorsConfig corsConfig = CorsConfigBuilder.forAnyOrigin()
                .allowedRequestMethods(HttpMethod.PUT,HttpMethod.DELETE,
                        HttpMethod.PATCH,HttpMethod.TRACE,HttpMethod.OPTIONS)
                .allowNullOrigin()
                .allowCredentials()
                .allowedRequestHeaders(CORS_ALLOW_HEADERS)
                .build();

        ChannelPipeline p = ch.pipeline();

        p.addLast(new HttpServerCodec());
        p.addLast(new HttpObjectAggregator(1024 * 1024 * 64));   // http合并包 设置最大长度 TODO:原理掌握
        p.addLast(new HttpServerExpectContinueHandler());
        p.addLast(new CorsHandler(corsConfig));
        p.addLast(new HttpServerHandler());
        p.addLast(new WebSocketServerProtocolHandler("/ws"));    // websoket连接
        p.addLast(new WebSocketHandler());
    }
}
